package com.ruoyi.web.controller.system;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.FaceLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/system/face")
public class FaceLoginController extends BaseController {

    @Autowired
    private FaceLoginService faceLoginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 人脸注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody Map<String, String> params) {
        Long userId = Long.parseLong(params.get("userId"));
        String image = params.get("image");
        boolean result = faceLoginService.registerFace(userId, image);
        return result ? success() : error("人脸注册失败");
    }

    /**
     * 人脸登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> params) {
        String image = params.get("image");
        String userId = faceLoginService.loginByFace(image);
        if (userId != null) {
            SysUser user = userService.selectUserById(Long.valueOf(userId));
            Set<String> permissions = userService.selectUserPermissions(user.getUserId());
            LoginUser loginUser = new LoginUser(
                    user.getUserId(),
                    user.getDeptId(),
                    user,
                    permissions
            );
            // 生成 Token（关键修改：直接调用 TokenService 生成 JWT，无需手动设置）
            String token = tokenService.createToken(loginUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            ajax.put("user", user);
            return ajax;
        } else {
            return error("人脸识别失败");
        }
    }
}